package com.itheima.algorithm.heap;

public class MinHeap{
    int[] array;
    int size;

    public MinHeap(int k) {
        this.array = new int[k];
        this.size = array.length;
        heapify();
    }

    /**
     * 建堆
     */
    public void heapify() {
        for (int i = size / 2 - 1; i >= 0; i--) {
            down(i);
        }
    }

    /**
     * 将 parent 索引处3的元素下潜：与两个孩子较大者交换，直至没孩子或孩子没它大
     * @param parent
     */
    public void down(int parent) {
        int left = parent * 2 + 1;
        int right = left + 1;
        int max = parent;
        if (left < size && array[max] > array[left]) {
            max = left;
        }
        if (right < size && array[max] > array[right]) {
            max = right;
        }
        if (max != parent) { // 找到了更大的孩子
            swap(max, parent);
            down(max);
        }
    }

    /**
     * 获取堆顶元素
     * @return 堆顶元素
     */
    public int peek() {
        return array[0];
    }

    /**
     * 替换堆顶元素
     * @param replaced - 新元素
     */
    public void replace(int replaced) {
        array[0] = replaced;
        down(0);
    }

    /**
     * 堆的尾部添加元素
     * @param offered - 被添加元素值
     * @return 是否添加成功
     */
    public boolean offer(int offered) {
        if (size == array.length) {
            return false;
        }
        up(offered);
        return true;
    }

    /**
     * 将 offered 元素上浮：直至 offered 小鱼父元素或到堆顶
     * @param offered
     */
    public void up(int offered) {
        int child = size;
        while (child > 0) {
            int parent = (child - 1) / 2;
            if (offered < array[parent]) {
                array[child] = array[parent];
            } else {
                break;
            }
            child = parent;
        }
        array[child] = offered;
    }


    /**
     * 交换两个索引处的元素
     * @param i
     * @param j
     */
    public void swap(int i, int j) {
        int t = array[i];
        array[i] = array[j];
        array[j] = t;
    }

    public boolean isFull() {
        return size == array.length;
    }
}